<template>
	<view>
		<!-- 收银台 -->
		<view class="edgeInsetTop"></view>
		<view class="wanl-pay">
			<view class="price-box">
				<text class="text-df">{{order_no}}</text>
				<text class="wanl-pip text-price margin-top-sm">{{price}}</text>
			</view>
			<view class="list-box">
				<view class="item" v-for="(item, index) in payList" :key="index" v-if="item.show">
					<text :class="'wlIcon-'+ (item.type == 'wechat'?'wechat':'balance') +'-pay'"></text>
					<view class="action">
						<text class="title wanl-pip">{{item.name}}</text>
						<view v-if="item.type == 'balance'">
							<text>可用余额 ￥{{user.can_balance}}</text>
						</view>
						<view v-else-if="item.type == 'bonus'">
							<text>可用余额 ￥{{user.can_bribe}}</text>
						</view>
						<view v-else-if="item.type == 'sell'">
							<text>可用余额 ￥{{user.can_money}}</text>
						</view>
						<view v-else-if="item.type == 'commission'">
							<text>可用余额 ￥{{user.can_commission}}</text>
						</view>
						<view v-else>{{item.describe}}</view>
					</view>
					<view class="radio text-xxl" v-if="item.state" @tap="onSelect(index)">
						<text v-if="item.select" class="wlIcon-xuanze-danxuan wanl-orange"></text>
						<text v-else class="wlIcon-xuanze wanl-gray-light"></text>
					</view>
					<view class="radio text-xxl" v-else>
						<text class="wlIcon-xuanze-danxuan wanl-gray-light"></text>
					</view>
				</view>
			</view>
			<view v-if="disabled">
				<button class="mix-btn wanl-bg-redorange"> <text
						class="wlIcon-jiazai wlIconfont-spin margin-right-xs"></text>正在支付中... </button>
			</view>
			<view v-else>
				<button v-if="payNum == 1" class="mix-btn wanl-bg-redorange" @tap="beforeConfirm()"> 确认支付 </button>
				<button v-else class="mix-btn wanl-bg-redorange" @tap="beforeConfirm()"> 合并支付 </button>
			</view>
			<view class="footer text-center">
				<!-- <view class="text-sm" v-if="order_pay_no">{{order_type === 'groups' ? '拼团':''}}交易号：{{order_pay_no}}</view> -->
				<!-- <view> © 万联支付</view> -->
			</view>
		</view>
		<view class="popup" v-if="popupShow" @click="popupShow = false">
			<view class="box" @click.stop>
				<view class="total-price flex just-between align-center">
					<view>支付总价：</view>
					<view>{{beforeConfirmData.price}}</view>
				</view>
				<view class="flex just-between align-center">
					<view>商品价格：</view>
					<view>{{beforeConfirmData.before_price}}</view>
				</view>
				<view class="flex just-between align-center">
					<view>手续费：</view>
					<view>{{beforeConfirmData.service_price}}</view>
				</view>
				<view class="popup-btn flex">
					<view class="popup-cancel" @click="popupShow = false">取消</view>
					<view class="popup-confirm" @click="confirm()">确定</view>
				</view>
			</view>
		</view>
		<passwordPopupVue :isShow.sync="isShowPwd" @onFinish="onFinish" />
	</view>
</template>

<script>
	import passwordPopupVue from "@/components/common/passwordPopup.vue";
	import {
		scanCreateOrder
	} from "@/API/home.js";
	import {
		mapState
	} from 'vuex';
	import {
		getOrderPrepose
	} from '@/API/order.js'
	import {
		getUserWallet
	} from '@/API/wallet.js'
	import {
		getUserIdenInfo
	} from '@/API/common.js'
	import func from '@/utils/func.js'
	export default {
		components: {
			passwordPopupVue
		},
		data() {
			return {
				token: '',
				disabled: false,
				price: '0.00',
				isbalance: false,
				order_type: 'goods',
				order_no: '',
				order_pay_no: '',
				payNum: 1, // 支付方式 独立支付-合并支付
				payList: [],

				popupShow: false,

				beforeConfirmData: {},

				from: '',
				passwordType: null,
				isShowPwd: false,
				payData: [],
				
				article_id:"",
			}
		},
		computed: {
			...mapState(['user'])
		},
		async onLoad(option) {
			if (option.article_id) {
				this.article_id = option.article_id;
			}
			if (option.from) this.from = option.from
			if (option.data) {
				var sum = 0,
					data = JSON.parse(option.data),
					order_ids = [];
				if (data.length <= 1) {
					this.price = data[0].price;
					this.order_type = data[0].type;
					this.order_no = `${data[0].type == 'groups' ? '拼团':''}订单号：${data[0].order_no}`;
					this.order_pay_no = data[0].pay_no;
					this.order_id = data[0].order_id;
				} else {
					data.forEach(item => {
						sum = this.$wanlshop.bcadd(sum, item.price);
						order_ids.push(item.order_id);
					});
					this.price = sum;
					this.order_id = order_ids;
					this.payNum = data.length;
					this.order_no = '合并支付 ' + data.length + '个订单';
				}
				this.token = option.token;
			} else if (option.order_id) {
				uni.showLoading({
					title: '结算中...'
				});
				await uni.request({
					url: '/wanlshop/pay/getPay',
					method: 'POST',
					data: {
						order_id: option.order_id,
						order_type: option.order_type
					},
					success: res => {
						uni.hideLoading();
						this.token = res.data.token;
						this.price = res.data.price;
						this.order_type = res.data.order_type;
						this.order_no =
							`${res.data.order_type == 'groups' ? '拼团':''}订单号：${res.data.order_no}`;
						this.order_pay_no = res.data.pay_no;
						this.order_id = res.data.order_id;
					}
				});
			} else {
				console.log('非法访问');
			}
			this.init()
		},
		onShow() {

			this.$commonNetwork.getUserIdenInfoData((res) => {
				this.passwordType = res.is_avoid;
			});
		},
		methods: {
			async init() {
				let {
					data: wallet
				} = await getUserWallet()
				let {
					data: user
				} = await getUserIdenInfo()

				this.$store.commit('user/setUserInfo', wallet);

				let hasWallet = []
				if (user.code === 1) hasWallet.push('money')
				if (user.partner_type !== null) hasWallet.push('commission')
				if (user.code === 0 || user.partner_type === 3) hasWallet.push('bribe')

				let totalBalance = func.bcadd(
					hasWallet.includes('money') ? wallet.can_money : 0,
					hasWallet.includes('bribe') ? wallet.can_bribe : 0,
					wallet.can_balance,
					hasWallet.includes('commission') ? wallet.can_commission : 0,
				)
				this.setPayList(totalBalance >= this.price * 1, hasWallet)

			},
			setPayList($balanceState, hasWallet) {
				this.payList = [{
					name: '微信支付',
					describe: '推荐使用微信支付',
					type: 'wechat',
					method: 'miniapp',
					state: true,
					select: true,
					show: true,
				}, {
					name: '余额支付',
					describe: '',
					type: 'balance',
					method: 'balance',
					select: false,
					state: $balanceState,
					show: true,
				}, {
					name: '红包钱包',
					describe: '',
					type: 'bonus',
					method: 'balance',
					select: false,
					state: $balanceState && this.user.can_bribe > 0,
					// show: hasWallet.includes('bribe')
					show: true,
				}, {
					name: '销售钱包',
					describe: '',
					type: 'sell',
					method: 'balance',
					select: false,
					state: $balanceState && this.user.can_money > 0,
					show: hasWallet.includes('money')
				}, {
					name: '分佣钱包',
					describe: '',
					type: 'commission',
					method: 'balance',
					select: false,
					state: $balanceState && this.user.can_commission > 0,
					show: hasWallet.includes('commission')
				}]
			},
			beforeConfirm() {
				this.payData = this.payList.filter(v => !!v.select).map(v => v.type)
				if (this.payData.length < 1) return this.$st.show('最少选择一种支付方式')
				// 选微信支付就一个值
				if (this.payData[0] != 'wechat') {
					if (this.passwordType === null) {
						this.$st.show("请设置支付密码", () => {
							this.$jump.to("/pages/mine/setting/payPassword")
						})
						return;
					}
					getOrderPrepose({
						method: this.payData.length > 0 ? 'make_up' : this.payData[0],
						order_type: this.order_type,
						pay_method: this.payData,
						price: this.price
					}).then(res => {
						this.beforeConfirmData = res.data
						this.beforeConfirmData.before_price = func.bcsub(
							res.data.price,
							res.data.service_price).toFixed(2)
						this.popupShow = true
					})
				} else {
					this.confirm()
				}
			},
			//确认支付
			confirm() {
				if (this.disabled) {
					return;
				}
				// console.log('-=-=data', data)
				// return
				if (this.payData.length < 1) return this.$st.show('最少选择一种支付方式')
				// 判断支付是否存在
				if (!this.payData.length) {
					uni.showModal({
						content: "请选择支付方式",
						showCancel: false
					});
					return;
				}
				
				if (this.payData[0] != 'wechat' && this.passwordType == 0) {
					this.isShowPwd = true;
					return;
				}
				
				this.onFinish('')

			},
			onFinish(pwd) {
				this.disabled = true;
				uni.login({
					success: (e) => {
						this.wanlPay(pwd, e.code);
					},
					fail: (e) => {
						uni.showModal({
							content: "无法获取微信code,原因为: " + e.errMsg,
							showCancel: false
						})
					}
				})
			},
			async wanlPay(password, code = null) {
				await uni.request({
					url: '/wanlshop/pay/payment',
					method: 'POST',
					data: {
						order_type: this.order_type,
						type: this.payData['0'] == 'wechat' ? 'wechat' : 'balance',
						method: this.payData.length > 1 ?
							'make_up' : (this.payData[0] == 'wechat' ?
								'miniapp' : this.payData[0]),
						code: code,
						order_id: this.order_id,
						token: this.token,
						pay_method: this.payData,
						password: password,
					},
					success: res => {
						if (this.payData[0] == 'wechat') {
							uni.requestPayment({
								appId: res.data.appId,
								nonceStr: res.data.nonceStr,
								package: res.data.package,
								paySign: res.data.paySign,
								signType: res.data.signType,
								timeStamp: res.data.timeStamp,
								success: (e) => {
									this.paySuccess();
								},
								fail: (e) => {
									if (this.order_type === 'goods' && this.from === '') {
										uni.switchTab({
											url: '/pages/tabBar/mine',
											success: res => {
												uni.navigateTo({
													url: '/pages/user/order/order?state=1'
												})
											}
										})
									} else if (this.order_type === "article") {
										this.$st.show("支付失败");
									}
									 
									 else {
										uni.navigateBack()
									}
									// uni.showModal({
									// 	content: "支付失败,原因为: " + e.errMsg,
									// 	showCancel: false
									// })
								}
							})
						} else {
							if (res.res.code == 0) {
								this.disabled = false;
								return this.$st.show(res.res.msg)
							}
							if (res.res.code == 1) {
								this.$store.commit('user/setUserInfo', {
									money: this.$wanlshop.bcsub(this.$store.state.user.money, this
										.price)
								});
								this.paySuccess();
							}
						}
					}
				});
			},
			onSelect(key) {
				if (this.payList[key].type == 'wechat') {
					this.payList.map((value, index, array) => {
						if (value.type != 'wechat') {
							value.select = false;
						} else {
							value.select = !value.select
						}
					});
				} else {
					this.payList.map((value, index, array) => {
						if (value.type == 'wechat') {
							value.select = false;
						} else {
							if (index == key) {
								value.select = !value.select
							}
						}
					});
				}
			},
			// 支付成功
			paySuccess() {
				this.disabled = false;
				if (this.order_type === 'goods') {
					this.$store.commit('statistics/order', {
						pay: this.$wanlshop.bcsub(this.$store.state.statistics.order.pay, this.payNum),
						delive: this.$wanlshop.bcadd(this.$store.state.statistics.order.delive, this.payNum)
					});
				}
				if (this.order_type === "article") {
					this.$jump.paySuccess("redBag", `&article_id=${this.article_id}`);
					return;
				}
				if (this.order_type === "top") {
					this.$jump.paySuccess("top");
					return;
				}
				this.$jump.paySuccess("pay");
			}
		}
	}
</script>

<style lang="less">
	page {
		background-color: white;
	}

	radio-group {
		display: block;
	}

	.popup {
		position: fixed;
		left: 0;
		top: 0;
		width: 100vw;
		height: 100vh;
		background-color: rgba(0, 0, 0, .5);
		display: flex;
		justify-content: center;
		align-items: center;

		.box {
			display: flex;
			flex-direction: column;
			padding: 30rpx;
			background-color: #fff;
			gap: 25rpx;
			border-radius: 15rpx;
			width: 400rpx;

			.total-price {
				text-align: center;
				font-size: 40rpx;
				height: 130rpx;
				border-bottom: 1px solid #aaa;
			}

			.popup-btn {
				gap: 10rpx;
				margin-top: 20rpx;

				view {
					display: flex;
					justify-content: center;
					align-items: center;
					padding: 15rpx 0;
					flex: 1;
					border-radius: 10rpx;
				}

				.popup-cancel {
					border: 1px solid #ddd;
					color: #ddd;
					background-color: #eee;
				}

				.popup-confirm {
					background-color: rgb(236, 109, 45);
					color: #fff;
				}
			}
		}
	}
</style>